package com.quarters.controller.wx;


import com.alibaba.fastjson.JSON;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.quarters.bean.ArticleOrder;
import com.quarters.bean.RoleQuarters;
import com.quarters.bean.User;
import com.quarters.commen.BaseController;
import com.quarters.util.Respons.ResponseUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 个人信息 前端控制器
 * </p>
 *
 * @author 冯政尚
 * @since 2019-09-02
 */
@Controller
@RequestMapping("wx/user")
public class WXUserController extends BaseController {


    /**
     * @return 支付成功
     */
    @RequestMapping(value = "successful_payment.html",method = RequestMethod.GET)
    public String successful_payment(){
        return "wx/successful_payment";
    }

    /**
     * @return 支付失败
     */
    @RequestMapping(value = "error_payment.html",method = RequestMethod.GET)
    public String error_payment(){
        return "wx/error_payment";
    }

    /**
     * @return 绑定成功
     */
    @RequestMapping(value = "bindingSuccess.html",method = RequestMethod.GET)
    public String bindingSuccess(){
        return "wx/bindingSuccess";
    }
    /**
     * @return 解绑成功
     */
    @RequestMapping(value = "bindingError.html",method = RequestMethod.GET)
    public String bindingError(){
        return "wx/bindingError";
    }

    /**
     * @param code
     * @param state
     * @param request
     * @return 微信登陆
     * @throws WxErrorException
     * @throws WxPayException
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @ApiOperation(value = "用户登陆")
    public String getUser(@ApiParam(name = "code", value = "微信回调的code", required = true) String code, String state, HttpServletRequest request) throws WxErrorException, WxPayException {

        //token换用户基本信息 如果出现异常 则说明是刷新  重新重定向授权地址
        try {
            //code换token
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = xbxWxService.getWxService().oauth2getAccessToken(code);

            WxMpUser wxMpUser = xbxWxService.getWxService().oauth2getUserInfo(wxMpOAuth2AccessToken, "zh_CN");
            User user = userService.login(wxMpUser);
            request.getSession().setAttribute("user", user);
        } catch (Exception e) {
            e.printStackTrace();
            //微信授权的地址
            String url = xbxWxService.getWxService().oauth2buildAuthorizationUrl(redirectURL, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
            return "redirect:" + url;
        }
        // xbxWxService.mpPayOrder();
        if (state != null && !state.equals("")) {
            return state;
        } else {
            return "redirect:/wx/user/make";
        }
    }





    /**
     * @return 未绑定小区
     */
//    @RequestMapping(value = "unbound.html",method = RequestMethod.GET)
//    public String unbound(){
//        return "wx/unbound";
//    }


    /**
     * @return 跳转是否解绑页面
     */
    @RequestMapping(value = "/personal", method = RequestMethod.GET)
    public String personal(HttpServletRequest request, Model model, HttpServletResponse response)throws IOException {
        if(getUser(request)==null){
            return "/wx/unbound";
        }else{
            User user = userService.getById(getUser(request).getId());
            System.out.println("解绑:"+user);
            if(user.getDetailedFloor()==null && user.getQuartersId()==null){
                return "wx/unbound";
            }else{
                HttpSession session = request.getSession();
                session.setAttribute("user", getUser(request));
                return "wx/personal";
            }
        }
    }

    /**
     * @return 跳转订单失效页面
     */
    @RequestMapping(value = "/error", method = RequestMethod.GET)
    public String error(HttpServletRequest request, Model model) {

        return "wx/error";
    }


    /**
     * @return 绑定小区
     */
    @RequestMapping(value = "make",method = RequestMethod.GET)
    public String make(Model model,HttpServletRequest request){
        if(getUser(request)==null){
            return "redirect:/wx/user/login";
        }else{
            User binding = userService.binding(getUser(request).getId());

            if(binding.getQuartersId()!=null && binding.getDetailedFloor()!=null){
                model.addAttribute("quarters",binding.getQuartersName());
                return "wx/binding";
            }
            HttpSession session = request.getSession();
            session.setAttribute("user", getUser(request));
            model.addAttribute("quarters",quartersService.list());
            return "wx/make";
        }

    }

    /**
     * @return 提示
     */
    @RequestMapping(value = "binding",method = RequestMethod.GET)
    public String binding(){
        return "wx/binding";
    }
    /**
     * @return 申请成功
     */
    @RequestMapping(value = "ok.html",method = RequestMethod.GET)
    public String ok(){
        return "wx/ok";
    }

    /**
     * @return 首页
     */
    @RequestMapping(value = "index",method = RequestMethod.GET)
    public String index(){
        return "wx/index";
    }
    /**
     * @return 报修
     */
    @RequestMapping(value = "repair",method = RequestMethod.GET)
    public String repair(HttpServletRequest request,Model model){
        HttpSession session = request.getSession();
        session.setAttribute("user", getUser(request));
        model.addAttribute("repair",repairService.list());
        return "wx/repair";
    }

    /**
     * @return 确认订单
     */
    @RequestMapping(value = "pay.html",method = RequestMethod.GET)
    public String pay(Model model,Long id){
        ArticleOrder articleOrder = articleOrderService.getById(id);

        if(articleOrder.getFlage()==1){
            return "wx/payment";
        }else{
            String result2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(articleOrder.getAuditTime());
            System.out.println("订单时间审核:"+result2);
            long currentTime = articleOrder.getAuditTime() + 60*60*1000;
            Date date = new Date(currentTime);
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String nowTime=df.format(date);
            System.out.println("60分钟---nowTime:"+nowTime);
            //获取当前系统时间的日期
            long time = System.currentTimeMillis();
            Date date1 = new Date(time);
            DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String nowTime1=df1.format(date1);
            System.out.println("现在时间---nowTime1:"+nowTime1);
            //前者大于后者返回大于0的数字 反之小于0
            System.out.println("结果:"+nowTime1.compareTo(nowTime));
            if(nowTime.compareTo(nowTime1)<0){
                return "wx/error";

            }else{
                model.addAttribute("articleOrder",articleOrder);
                return "wx/pay";
            }
        }
    }

    /**
     * @return 完成订单
     */
    @RequestMapping(value = "success_pay.html",method = RequestMethod.GET)
    public String success_pay(Long id,Model model) throws WxErrorException, WxPayException {
        ArticleOrder articleOrder = articleOrderService.getById(id);
        //查询支付订单管理员的openid
        //User user =  userService.selectPayOpenId(articleOrder.getId());
        System.out.println("支付:"+articleOrder.getOpenid());
        model.addAttribute("data",articleOrderService.successPay(articleOrder));
        model.addAttribute("moeny",articleOrder.getOrderMoeny());
        return "wx/success_pay";
    }


    /**
     * @param param
     * @param request
     * @return 用户添加详细信息
     * @throws SQLException
     */
    @RequestMapping(value = "updateByIdUser", method = RequestMethod.POST)
    @ResponseBody
    public Map updateByIdUser(String param, HttpServletRequest request) throws SQLException {
        User binding = userService.binding(getUser(request).getId());
        if(binding.getQuartersId()!=null && binding.getDetailedFloor()!=null){
            return ResponseUtil.RequestException("您已绑定小区!");
        }else{
            User user = JSON.parseObject(param, User.class);
            if(userService.updateById(user)){
                return ResponseUtil.getSuccessMap();
            }
            return ResponseUtil.getExceptionMap();
        }

    }

    @RequestMapping(value = "admin",method = RequestMethod.GET)
    public String admin(){
        return "wx/admin";
    }

    /**
     * @param userId
     * @return 解绑
     */
    @RequestMapping(value = "untying",method = RequestMethod.POST)
    @ResponseBody
    public String untying(Long userId,HttpServletRequest request){
        User user = userService.getById(userId);
        System.out.println("解绑:"+user);
        if(getUser(request)==null){
            return "redirect:/wx/user/login";
        }

        RoleQuarters roleQuarters = roleQuartersService.selectByOpenId(user.getOpenid());
        if(roleQuarters!=null){
            if(roleQuarters.getFlage()==1 || roleQuarters.getFlage()==2){
                return "3";
            }
        }
        if(user.getTel()==null && user.getQuartersId()==null && user.getDetailedFloor()==null){
            return "2";
        }else{
            return userService.untying(userId)+"";
        }




    }

    /**
     * @return 咨询订单支付成功回调
     */
    @RequestMapping(value = "/paySuccess")
    @ResponseBody
    public void paySuccess(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter printWriter = response.getWriter();
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            WxPayOrderNotifyResult result = xbxWxService.getConsultationWxPayService().parseOrderNotifyResult(xmlResult);
            // 结果正确
            String myOrderId = result.getOutTradeNo();
            String wxOrderId = result.getTransactionId();
            String totalFee = result.getTotalFee()+"";
            System.out.println("回调:"+myOrderId);
            System.out.println("回调:"+wxOrderId);
            System.out.println("回调:"+totalFee);
            //处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
            articleOrderService.paySuccess(myOrderId, wxOrderId, totalFee);
           // articleOrderService.send(  myOrderId);


            printWriter.print(WxPayNotifyResponse.success("处理成功!"));
        } catch (Exception e) {
            e.printStackTrace();
            printWriter.print(WxPayNotifyResponse.fail(e.getMessage()));
        } finally {
            printWriter.close();
        }
    }


}
